package com.aw.baselib.util.update;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.aw.baselib.R;
import com.aw.baselib.base.AwBaseApplication;
import com.aw.baselib.base.AwViewDialog;
import com.aw.baselib.interfaces.IPermissionListener;
import com.aw.baselib.util.AwAppUtils;
import com.aw.baselib.util.AwDataUtil;
import com.aw.baselib.util.AwLog;
import com.aw.baselib.util.AwRxPermissionUtil;
import com.aw.baselib.util.AwToastUtil;

import java.io.File;

import androidx.annotation.RequiresApi;
import androidx.core.content.FileProvider;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;

/**
 * Created by hzw
 */

public class AwUpdateUtil {

    private static Activity mActivity;
    private static AwUpdateUtil instance;
    protected static AwViewDialog mDialog;
    protected static AwViewDialog m4gDialog;
    protected static AwViewDialog mDownloadDialog;


    public static AwUpdateUtil getInstance(Activity activity) {
        if(instance == null) {
            return new AwUpdateUtil(activity);
        }
        showDownloadDialog();
        return instance;
    }

    public AwUpdateUtil(Activity activity) {
        mActivity = activity;
        showDownloadDialog();
    }

    private static void showDownloadDialog() {
        mDialog = new AwViewDialog(mActivity);
        m4gDialog = new AwViewDialog(mActivity);
        mDownloadDialog = new AwViewDialog(mActivity);
    }

    public void handleUpdate(final UpdateBean updateBean, final IUpdateCancelInterface iUpdateCancelInterface) {
        // 需要版本更新 展示弹框
        String textContent = AwBaseApplication.getInstance().getString(R.string.update_version) + updateBean.getAppVersion() + "\n\n" +
                AwBaseApplication.getInstance().getString(R.string.update_content) + "\n" + updateBean.getDescription();
        mDialog.showUpdateDialog(textContent, !updateBean.isForceUpdate(), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    boolean hasInstallPermission = mActivity.getPackageManager().canRequestPackageInstalls();
                    if (!hasInstallPermission) {
                        startInstallPermissionSettingActivity();
                        return;
                    }
                }
                if(!updateBean.isForceUpdate()) {
                    mDialog.dismiss();
                }
                AwRxPermissionUtil.getInstance().checkPermissions(mActivity, AwRxPermissionUtil.getStoragePermissions(), new IPermissionListener() {
                    @Override
                    public void granted() {
                        if (AwBaseApplication.netWatchdog.hasNet(mActivity)) {
                            if (AwBaseApplication.netWatchdog.is4GConnected(mActivity)) {
                                m4gDialog.showCommonDialog(mActivity.getString(R.string.update_hint_is_not_wifi), AwBaseApplication.getInstance().getString(R.string.common_cancel),
                                        AwBaseApplication.getInstance().getString(R.string.common_confirm), false, true, true,
                                        v1 -> {
                                            m4gDialog.dismiss();
                                            if (updateBean.isForceUpdate()) {
                                                mActivity.finish();
                                            }
                                        }, v12 -> {
                                            m4gDialog.dismiss();
                                            downloadFile(mActivity, updateBean.getAppurl(), iUpdateCancelInterface);
                                        });
                            } else {
                                downloadFile(mActivity, updateBean.getAppurl(), iUpdateCancelInterface);
                            }
                        }
                    }

                    @Override
                    public void shouldShowRequestPermissionRationale() {
                        AwToastUtil.showShort(AwBaseApplication.getInstance(), mActivity.getString(R.string.update_hint_permission_1));
                        iUpdateCancelInterface.cancelUpdate();
//                                mActivity.finish();
                    }

                    @Override
                    public void needToSetting() {
                        AwToastUtil.showShort(AwBaseApplication.getInstance(), mActivity.getString(R.string.update_hint_permission_1));
                        iUpdateCancelInterface.cancelUpdate();
//                                AwSystemIntentUtil.toSelfSetting(mActivity);
                    }
                });
            }
        }, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
                iUpdateCancelInterface.cancelUpdate();
            }
        });
    }

    private static void downloadFile(final Activity activity, final String url, final IUpdateCancelInterface iUpdateCancelInterface) {
        if (AwDataUtil.isEmpty(url)) {
            AwToastUtil.showShort(activity, AwBaseApplication.getInstance().getString(R.string.update_download_url_empty));
            mDownloadDialog.dismiss();
            iUpdateCancelInterface.cancelUpdate();
            return;
        }
        mDownloadDialog.showDownloadDialog();
        final ProgressBar pb_loading = (ProgressBar) mDownloadDialog.getDialog().findViewById(R.id.pb_loading);
        TextView btn_cancel = (TextView) mDownloadDialog.getDialog().findViewById(R.id.btn_cancel);
        final TextView tv_progress = (TextView) mDownloadDialog.getDialog().findViewById(R.id.tv_progress);
        pb_loading.setMax(100);
        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AwFileDownloadUtil.get().cancel(activity, url);
                mDownloadDialog.dismiss();
                iUpdateCancelInterface.cancelUpdate();
            }
        });
        AwFileDownloadUtil.get().downApk(activity, url, new AwFileDownloadUtil.OnDownloadListener() {
            @Override
            public void onDownloadSuccess(String path) {
                Observable.just(path).observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Consumer<String>() {
                            @Override
                            public void accept(String s) throws Exception {
                                Toast.makeText(activity, AwBaseApplication.getInstance().getString(R.string.download_success), Toast.LENGTH_SHORT).show();
                                mDownloadDialog.dismiss();
                                openAPKFile(mActivity, s);
                            }
                        });
            }

            @Override
            public void onDownloading(final int progress) {
                Observable.just(progress).observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Consumer<Integer>() {
                            @Override
                            public void accept(Integer integer) throws Exception {
                                pb_loading.setProgress(progress);
                                tv_progress.setText(progress + "%");
                            }

                        });
            }

            @Override
            public void onDownloadFailed(String path) {
                Observable.just(0).observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Consumer<Integer>() {
                            @Override
                            public void accept(Integer integer) throws Exception {
                                Toast.makeText(activity, AwBaseApplication.getInstance().getString(R.string.download_success), Toast.LENGTH_SHORT).show();
                                AwFileDownloadUtil.get().cancel(activity, url);
                                mDownloadDialog.dismiss();
                                iUpdateCancelInterface.cancelUpdate();
                            }
                        });

            }

            @Override
            public void onDownloadIngRejectRepeat() {

            }
        });
    }

    /**
     * 打开安装包
     *
     * @param mContext
     * @param fileUri
     */
    public static void openAPKFile(Activity mContext, String fileUri) {
        // 核心是下面几句代码
        if (null != fileUri) {
            try {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                File apkFile = new File(fileUri);
                //兼容7.0
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    Uri contentUri = FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".base.fileProvider", apkFile);
                    intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
                    //兼容8.0
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        boolean hasInstallPermission = mContext.getPackageManager().canRequestPackageInstalls();
                        if (!hasInstallPermission) {
                            startInstallPermissionSettingActivity();
                            return;
                        }
                    }
                } else {
                    intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                }
                if (mContext.getPackageManager().queryIntentActivities(intent, 0).size() > 0) {
                    mContext.startActivity(intent);
                }
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 跳转到设置-允许安装未知来源-页面
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    private static void startInstallPermissionSettingActivity() {
        //注意这个是8.0新API
//        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:" + mActivity.getPackageName()));
//        mActivity.startActivityForResult(intent, 333);

        Intent intent = new Intent();
        //获取当前apk包URI，并设置到intent中（这一步设置，可让“未知应用权限设置界面”只显示当前应用的设置项）
        Uri packageURI = Uri.parse("package:"+ mActivity.getPackageName());
        intent.setData(packageURI);
        //设置不同版本跳转未知应用的动作
        if (Build.VERSION.SDK_INT >= 26) {
            //intent = new Intent(android.provider.Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES,packageURI);
            intent.setAction(android.provider.Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
        }else {
            intent.setAction(android.provider.Settings.ACTION_SECURITY_SETTINGS);
        }
//        mActivity.startActivityForResult(intent, 333);
        mActivity.startActivity(intent);
    }
}
